<?php

namespace app\api\controller;

use app\admin\model\department\Lists;
use app\admin\model\District;
use app\admin\model\express\Companys;
use app\admin\model\money\Change;
use app\admin\model\month\Salary;
use app\admin\model\product\Listo;
use app\admin\model\product\Order;
use app\admin\model\Signs;
use app\admin\model\total\Bill;
use app\admin\model\user\Finance;
use app\admin\model\user\Invest;
use app\admin\model\user\Sign;
use app\admin\model\user\Statics;
use app\common\controller\Api;
use app\common\controller\Bonus;
use app\common\controller\Kd100;
use app\common\model\Area;
use app\common\model\Config;
use app\company\controller\Usersign;
use think\Exception;
use think\Request;
use think\Db;

/**
 * 地址接口
 */
class Task extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected $model = null;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);

    }

    /**
     * 补充订阅物流信息
     */
    public function logisticsSbAgain()
    {
        $time1 = time() - 3 * 24 * 60 * 60;
        $time2 = time() - 0 * 24 * 60 * 60 - 86000;
        $lists = Listo::field('id,tool,toolid,order_id,backinfo')
            ->where('status', 10)
            ->where('createtime', '>=', $time1)
//            ->where('createtime', '<', $time2)
            ->order('id asc')->select();

        foreach ($lists as $val1) {
            $info = Db::name('kd_info')->where('tool', $val1->tool)->find();
//            var_dump(Db::name('kd_info')->getLastsql());die;
            if ($info) {
                continue;
            }

//            var_dump($val1->id);
            // 物流信息订阅
            $toolInfo = Companys::where('id', $val1->toolid)->find();
            if (!$toolInfo) {
                write_log('id为' . $val1->id . '的订单物流公司不存在', 'wuliu');
            }
            $addressId = \app\admin\model\product\Order::where('id', $val1->order_id)->value('addressid');
            $mobile = \app\admin\model\Transport::where('id', $addressId)->value('mobile');

            $ret = (new Kd100())->logisticsSb($toolInfo->code, $val1->tool, $mobile);
            if ($ret['code'] == 0) {
                write_log('id为' . $val1->id . '的订单报错：' . $ret['error_code'] . $ret['msg'], 'wuliu_eror');
            }
        }

        echo 'success';
        die;
    }

    public function logisticsSbAgaincs()
    {
        $time1 = time() - 10 * 24 * 60 * 60;
        $time2 = time() - 0 * 24 * 60 * 60 - 86000;
        $lists = Listo::field('id,tool,toolid,order_id,backinfo')
            ->where('status', 10)
            ->where('createtime', '>=', $time1)
            ->where('createtime', '<', $time2)
            ->order('id asc')->select();
//        var_dump($lists);
//        die;
        foreach ($lists as $val1) {
            $toolInfo = Companys::where('id', $val1->toolid)->find();
            $addressId = \app\admin\model\product\Order::where('id', $val1->order_id)->value('addressid');
            $mobile = \app\admin\model\Transport::where('id', $addressId)->value('mobile');
            $data = (new Kd100())->logisticsInfo($toolInfo->code, $val1->tool, $mobile);
            if ($data['code'] == 0) {
                continue;
            }

            $state = $data['res']['state'];
            $time = strtotime($data['res']['data'][0]['time']);
            if ($state == 3) {
                // 签收
                $ldata = [
                    'status' => 20,
                    'backinfo' => 'success',
                    'finish_time' => $time,
                    'updatetime' => $time
                ];
//                var_dump($val1->id);die;
                Db::name('product_listo')->where('id', $val1->id)->update($ldata);
                $num = Listo::where('order_id', $val1->order_id)->where('status', 'lt', 20)->count();
                if ($num == 0) {
                    Db::name('product_order')->where('id', $val1->order_id)->update($ldata);
                }
            }

//            die;
        }

        echo 'success';
        die;
    }

    /**
     * 订单失败（15天）
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function failOrder()
    {
        $time = 15 * 24 * 60 * 60;
        $now = time();
        $orders = Order::where('status', '>=', 10)->where('status', '<', 20)->order('id asc')->select();

        if (!$orders) {
            echo '无可执行订单';
            die;
        }
        foreach ($orders as $val) {
            if ($val->backinfo == 'fail') {
                continue;
            }

            if ($now - $val->send_time < $time) {
                continue;
            }

            // 超时取消订单
            $val->backinfo = 'fail';
            $val->updatetime = time();
            $val->save();

            Listo::where('order_id', $val->id)->update(['backinfo' => 'fail', 'updatetime' => time()]);

            $content = '您好，订单' . $val->orderid . '的商品已被退回，产生物流损耗' . $val->transfee . '元';
            $type = 'cost';
            $department_user_id = $val->department_user_id;
            $ndata = [
                'user_id' => $department_user_id,
                'type' => $type,
                'relation_id' => $val->id,
                'content' => $content,
                'is_read' => 0,
            ];
            \app\admin\model\Notices::create($ndata);

            $user = \app\admin\model\department\User::find($department_user_id);
            if ($user->is_leader == 0) {
                $luser = \app\admin\model\department\User::where('department_id', $user->department_id)
                    ->where('is_leader', 1)
                    ->find();
                if ($luser) {
                    $ndata = [
                        'user_id' => $luser->id,
                        'type' => $type,
                        'relation_id' => $val->id,
                        'content' => $content,
                        'is_read' => 0,
                    ];
                    \app\admin\model\Notices::create($ndata);
                }
            }
        }

        echo 'success';
        die;
    }

    /**
     * 统计底薪
     */
    public function monthSalary()
    {
        $users = \app\admin\model\department\User::where('type', 1)->where('status', 'normal')->order('id asc')->select();
        if (!$users) {
            echo '暂无员工';
            die;
        }

        $last_mont_first_date = strtotime(date('Y-m-1', time()));
        $last_mont_end_date = strtotime(date('Y-m-d', time())) + 86400;

        $days = floor(($last_mont_end_date - $last_mont_first_date) / 86400) + 1;
        foreach ($users as $val) {

            $signConfig = sign_config($val->id);
            $signConfig1 = array_slice($signConfig, 0, 2);
            $signConfig2 = array_slice($signConfig, 2, 2);

            $where = [
                'user_id' => $val->id,
                'datetime' => $last_mont_first_date,
            ];

            $row = Salary::where($where)->find();

            $total_num = 0;
            for ($i = 0; $i < $days; $i++) {
                $date = date('Y-m-d', $last_mont_first_date + $i * 86400);
                $num1 = $this->getNum($signConfig1, $val->id, $date);
                $total_num += $num1;

                $num2 = $this->getNum($signConfig2, $val->id, $date);
                $total_num += $num2;
            }

            $money = round($val->day_salary / 2, 2);
            $salary = $total_num * $money;

            if ($row) {
                $row->salary = $salary;
                $row->save();
            } else {
                $where['salary'] = $salary;
                Salary::create($where);
            }
        }

        echo '统计完成';
        die;
    }

    /**
     * 判断是否签到
     * @param $signConfig
     * @param $userId
     * @param $date
     * @return int
     */
    private function getNum($signConfig, $userId, $date)
    {
        $tnum = 0;
        $num1 = 0;
        foreach ($signConfig as $v1) {
            $start1 = strtotime($date . $v1[0]);
            $end1 = strtotime($date . $v1[1]);
            $where = [
                'user_id' => $userId,
                'createtime' => [['>=', $start1], ['<', $end1]]
            ];
            $sign = Sign::where($where)->find();

            if ($sign) {
                $num1 += 1;
            }

        }

        if ($num1 >= 2) {
            $tnum += 1;
        }

        return $tnum;
    }

    /**
     * 统计今日缺卡员工
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function queSign()
    {
        $ids = Lists::where('status', 'normal')->where('name', '<>', '董事长')->column('id');
        $lists = \app\admin\model\department\User::field('id,username')
            ->where('department_id', 'in', $ids)
            ->where('status', 'normal')
            ->where('is_leave', 0)
            ->select();

//        $today_date1 = '2025-2-16';
        $today_time = strtotime('today');
        for ($i = 0; $i < 1; $i++) {
            $today = $today_time + $i * 86400;
            $today_date = date('Y-m-d', $today);
//            var_dump($today, $today_date);
//            die;
            $time_str = [
                0 => '上午上班',
                1 => '上午下班',
                2 => '下午上班',
                3 => '下午下班',
            ];
            foreach ($lists as $item) {
                $userId = $item->id;
                $num = Sign::where('user_id', $userId)
                    ->where('createtime', '>=', $today)
                    ->where('createtime', '<', $today + 86400)
                    ->count();

                if ($num < 4) {
                    $data = sign_config($item->id);
                    $str = [];
                    foreach ($data as $key => $val) {
                        $begin = strtotime($today_date . ' ' . $val[0]);
                        $end = strtotime($today_date . ' ' . $val[1]);
//                    var_dump($today_date . ' ' . $val[0]);
//                    die;
                        $where = [
                            'createtime' => [['>=', $begin], ['<', $end]],
                            'user_id' => $userId,
                        ];
                        $sinfo = Sign::where($where)->find();
                        if (!$sinfo) {
                            $str[] = $time_str[$key];
                        }
                    }

                    $sdata = [
                        'date' => $today,
                        'user_id' => $userId,
                        'num' => (4 - $num),
                        'remark' => implode(',', $str),
                    ];
                    Signs::create($sdata);
                }
            }
        }


        $this->success('统计完成');
    }

    /**
     * 厨师补卡
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function buSign()
    {
        $ids = [13, 14];
        $lists = \app\admin\model\department\User::field('id,username')
            ->where('department_id', 'in', $ids)
            ->where('status', 'normal')
            ->select();

        $now = time();
        foreach ($lists as $item) {
            $userId = $item->id;
            $data = sign_config($userId);
            unset($data[0], $data[1]);
            foreach ($data as $val) {
                $isSign = Sign::where('user_id', $userId)
                    ->where('createtime', '>=', $val[0])
                    ->where('createtime', '<', $val[1])
                    ->find();
                if (!$isSign) {
                    $sdata = [
                        'user_id' => $userId,
                        'createtime' => $now
                    ];

                    Sign::create($sdata);
                }
            }
        }

        echo '补卡完成';
        die;
    }

    /**
     * 冻结奖励
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function freeze_year_bonus()
    {
        $lists = \app\admin\model\department\User::where('status', 'normal')
            ->where('is_year_bonus', 1)
            ->where('is_unfreeze_year_bonus', 0)
            ->order('id asc')
            ->select();
        if (!$lists) {
            echo '无数据';
            die;
        }

        $now = time();
        foreach ($lists as $user) {
            // 超过7天未打卡激励收益归零
            $userId = $user->id;
            $lastSignTime = Sign::where('user_id', $userId)->order('id desc')->value('createtime');
            if ($lastSignTime) {
                $times = 7 * 24 * 60 * 60;
                if ($now - $lastSignTime >= $times) {
                    $user->has_year_bonus = 0;
                    $user->save();
                }
            }
        }
        echo 'success';
        die;
    }

    /**
     * 上午统计激励收益和月薪
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getBonus1()
    {
        $lists = \app\admin\model\department\User::where('status', 'normal')
            ->order('id asc')
            ->select();
        if (!$lists) {
            echo '无数据';
            die;
        }
        $now = time();
        foreach ($lists as $user) {
            $userId = $user->id;
            $data = sign_config($userId);
            unset($data[2], $data[3]);

            $num = 0;
            foreach ($data as $val) {
                $begin = strtotime($val[0]);
                $end = strtotime($val[1]);
                $where = [
                    'createtime' => [['>=', $begin], ['<', $end]],
                    'user_id' => $userId,
                ];
                $sinfo = Sign::where($where)->find();
                if ($sinfo) {
                    $num += 1;
                }
            }

            if ($num == 2) {
                // 添加激励收益（冻结中才可以）
                if ($user->is_year_bonus == 1 && $user->is_unfreeze_year_bonus == 0) {
                    $half_year_bonus = config('site.half_year_bonus');
                    $total_year_bonus = config('site.total_year_bonus');
                    $user->has_year_bonus += $half_year_bonus;
                    if ($user->has_year_bonus >= $total_year_bonus) {
                        $user->has_year_bonus = $total_year_bonus;
                        $user->is_unfreeze_year_bonus = 1;
                    }
                    $user->save();
                }

                if ($user->type == 1) {
                    // 员工增加月薪
                    $salary = round($user->day_salary / 2, 2);
                    $month = strtotime(date('Y-m', $now));
                    $where = [
                        'user_id' => $userId,
                        'datetime' => $month,
                    ];

                    $row = Salary::where($where)->find();
                    if ($row) {
                        $row->salary += $salary;
                        $row->save();
                    } else {
                        $where['salary'] = $salary;
                        $ret = Salary::create($where);
                    }
                }
            }
        }

        echo '奖励发放成功';
        die;
    }

    /**
     * 下午统计激励收益和月薪
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getBonus2()
    {
        $lists = \app\admin\model\department\User::where('status', 'normal')
            ->order('id asc')
            ->select();
        if (!$lists) {
            echo '无数据';
            die;
        }
        $now = time();
        foreach ($lists as $user) {
            $userId = $user->id;
            $data = sign_config($userId);
            unset($data[0], $data[1]);
            $num = 0;
            foreach ($data as $val) {
                $begin = strtotime($val[0]);
                $end = strtotime($val[1]);
                $where = [
                    'createtime' => [['>=', $begin], ['<', $end]],
                    'user_id' => $userId,
                ];

                $sinfo = Sign::where($where)->find();
                if ($sinfo) {
                    $num += 1;
                }
            }

            if ($num == 2) {
                // 添加激励收益（冻结中才可以）
                if ($user->is_year_bonus == 1 && $user->is_unfreeze_year_bonus == 0) {
                    $half_year_bonus = config('site.half_year_bonus');
                    $total_year_bonus = config('site.total_year_bonus');
                    $user->has_year_bonus += $half_year_bonus;
                    if ($user->has_year_bonus >= $total_year_bonus) {
                        $user->has_year_bonus = $total_year_bonus;
                        $user->is_unfreeze_year_bonus = 1;
                    }
                    $user->save();
                }

                if ($user->type == 1) {
                    // 员工增加月薪
                    $salary = round($user->day_salary / 2, 2);
                    $month = strtotime(date('Y-m', $now));
                    $where = [
                        'user_id' => $userId,
                        'datetime' => $month,
                    ];

                    $row = Salary::where($where)->find();
                    if ($row) {
                        $row->salary += $salary;
                        $row->save();
                    } else {
                        $where['salary'] = $salary;
                        $ret = Salary::create($where);
                    }
                }
            }
        }

        echo '奖励发放成功';
        die;
    }
}
